import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getTimeStamp } from './auth'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
service.interceptors.request.use(config => {
  if (store.getters.token) {
    // 发请求前,先主动判断token是否超时
    if (checkTimeout()) {
      store.commit('user/logout')
      router.push('/login')
      return Promise.reject(new Error('密钥超时,请重新登录'))
    }
    // Bearer后面一定要带空格
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }
  return config
})

service.interceptors.response.use(res => {
  const { success, message, data } = res.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.commit('user/logout')
    router.push('/login')
  }
  Message.error(err.message)
  return Promise.reject(new Error(err.message))
})

export default service

function checkTimeout() {
  const now = Date.now()
  const timeKey = getTimeStamp()
  return (now - timeKey) / 60000 > 120
}
